package com.lxk.handler;

import com.lxk.exception.UnloginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Lxk on 2020/6/11.
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${addr.prefix}")
    private String addrPrefix;

    @ExceptionHandler({UnloginException.class,HttpRequestMethodNotSupportedException.class})
    public ModelAndView unloginException(HttpServletRequest request,HttpServletResponse response,Exception e) throws IOException {
        response.sendRedirect("http://"+addrPrefix+"/admin");
        logger.info("e:",e);
        return null;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception ex) throws Exception {
        logger.error("request url:{},exception:{}",request.getRequestURL(),ex);
        if(AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class)!=null){
            throw ex;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception",ex);
        mv.setViewName("error/error");
        return mv;
    }



}
